package com.vic.geektime.math.chapter01;

/**
 *  @title 十进制转二进制的三种方法
 *  @Description 1.余数短除法；2.降二次幂及减法混合运算；3.位运算法
 *  @author Karson Wang
 *  @Date 2020/3/26 9:32
 *  @Copyright 2019-2020 
 */
public class Lesson1_append2 {
    //
    public static void main(String[] args) {

        int loopCount = 10000000;// 循环一千万次
        long start = 0, end = 0;
        start = System.currentTimeMillis();
        for (int i = 0; i < loopCount; i++)
            decimalToBinaryA(53);
        end = System.currentTimeMillis();
        System.out.println(end - start);// 执行时间652ms

        start = System.currentTimeMillis();
        for (int i = 0; i < loopCount; i++)
            decimalToBinaryB(53);
        end = System.currentTimeMillis();
        System.out.println(end - start);// 执行时间4316ms

        start = System.currentTimeMillis();
            for (int i = 0; i < loopCount; i++)
                decimalToBinaryC(53);
        end = System.currentTimeMillis();
        System.out.println(end - start);// 执行时间730ms
    }


    /**
     * @Title: decimalToBinary
     * @Description: 十进制转二进制，方法1：余数短除法[ 除以二]
     * @param decimalSource
     * @return: String
     */
    public static String decimalToBinaryA(int decimalSource) {
        StringBuilder sb = new StringBuilder();
        while (decimalSource != 0) {
            sb.append(decimalSource % 2);
            decimalSource = decimalSource >> 1;
        }
        return sb.reverse().toString();
    }

    /**
     * @param decimalSource
     * @Title: decimalToBinary
     * @Description: 十进制转二进制，方法2：降二次幂及减法混合运算
     * @return: String
     */
    public static String decimalToBinaryB(int decimalSource) {
        int length = (int) (Math.log(decimalSource) / Math.log(2));
        StringBuffer sb = new StringBuffer();
        do {
            decimalSource = (int) (decimalSource - Math.pow(2, length));
            int power = decimalSource <= 0 ? -1 : (int) (Math.log(decimalSource) / Math.log(2));
            for (int i = length; i > power; i--) {
                if (i == length) {
                    sb.append("1");
                } else {
                    sb.append("0");
                }
            }
            length = power;
        } while (decimalSource > 0);
        return sb.toString();
    }

    /**
     * @param decimalSource
     * @return
     * @Title: decimalToBinary
     * @Description: 十进制转二进制，方法3：位运算法
     * @return: String
     */
    public static String decimalToBinaryC(int decimalSource) {
        StringBuffer sb = new StringBuffer();
        while (decimalSource != 0) {
            //此&运算，decimalSource & 1，目的是获取最低位的二进制数值
            sb.append(decimalSource & 1);
            //此>>运算，decimalSource >> 1，目的是将获取到的最低位二进制数值除去
            decimalSource = decimalSource >> 1;
        }
        return sb.reverse().toString();
    }
}
